package org.jeecg.modules.register.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.Md5Util;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.register.entity.AgencyLegal;
import org.jeecg.modules.register.entity.AgencyLegal;
import org.jeecg.modules.register.entity.AgencyLegalCheckLog;
import org.jeecg.modules.register.entity.SubjectLegal;
import org.jeecg.modules.register.mapper.AgencyLegalCheckLogMapper;
import org.jeecg.modules.register.mapper.AgencyLegalFileMapper;
import org.jeecg.modules.register.mapper.AgencyLegalMapper;
import org.jeecg.modules.register.service.IAgencyLegalService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Description: agency_legal
 * @Author: jeecg-boot
 * @Date:   2024-12-17
 * @Version: V1.0
 */
@Service
public class AgencyLegalServiceImpl extends ServiceImpl<AgencyLegalMapper, AgencyLegal> implements IAgencyLegalService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    public AgencyLegalMapper agencyLegalMapper;


    @Resource
    public AgencyLegalCheckLogMapper agencyLegalCheckLogMapper;

    @Resource
    public AgencyLegalFileMapper agencyLegalFileMapper;

    @Resource
    private BaseCommonService baseCommonService;

    @Resource
    private ISysUserService sysUserService;

    @Override
    public Result<AgencyLegal> registe(AgencyLegal agencyLegal) {

        //验证验证码是否正确
        String captcha = agencyLegal.getCheckCode();
        String checkKey = agencyLegal.getCheckKey();
        if(captcha==null){
            return Result.error("验证码无效");
        }
        String lowerCaseCaptcha = captcha.toLowerCase();
        String realKey = Md5Util.md5Encode(lowerCaseCaptcha+checkKey, "utf-8");
        Object checkCode = redisUtil.get(realKey);
        if(checkCode==null || !checkCode.equals(lowerCaseCaptcha)) {
            return Result.error("验证码错误");
        }


        if(StringUtils.isEmpty(agencyLegal.getAgencyId())){
            QueryWrapper<AgencyLegal> queryWrapper = new QueryWrapper<AgencyLegal>();
            queryWrapper.eq(StringUtils.isNotEmpty(agencyLegal.getLegalCode()),"legal_code", agencyLegal.getLegalCode());

            List<AgencyLegal> list = agencyLegalMapper.selectList(queryWrapper);
            if(list.size() > 0){
                return Result.error("法人主体已经注册，请登陆之后再完成注册信息填写！");
            }

            SysUser user = trunUserByAgencyLegal(agencyLegal);

            //管理员账号信息插入
            if(!addSysUserInfo(user)){
                return Result.error("注册失败，请联系管理员！");
            }


            agencyLegal.setState("0");
            agencyLegal.setSysUserId(user.getId());
            agencyLegal.setPassword("");
            agencyLegalMapper.insert(agencyLegal);

            //file 表里插入两条数据
            agencyLegalFileMapper.insertAgencyInitFile(agencyLegal);


            AgencyLegal agencyLegalNew = agencyLegalMapper.selectOne(queryWrapper);
            //登陆返回token
            String token = JwtUtil.sign(user.getUsername(), user.getPassword());
            // 设置token缓存有效时间
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
            agencyLegalNew.setToken(token);

            return Result.ok(agencyLegalNew);
        }else{
            QueryWrapper<AgencyLegal> queryWrapper = new QueryWrapper<AgencyLegal>();
            queryWrapper.eq("agency_id", agencyLegal.getAgencyId());
            List<AgencyLegal> list = agencyLegalMapper.selectList(queryWrapper);
            if(list.size() == 1){
                agencyLegalMapper.updateById(agencyLegal);
            }
            AgencyLegal agencyLegalNew = agencyLegalMapper.selectOne(queryWrapper);
            return Result.ok(agencyLegalNew);
        }
    }

    @Override
    public void submitCheck(AgencyLegal agencyLegal) {

        QueryWrapper<AgencyLegal> queryWrapper = new QueryWrapper<AgencyLegal>();
        queryWrapper.eq("agency_id", agencyLegal.getAgencyId());
        List<AgencyLegal> list = agencyLegalMapper.selectList(queryWrapper);
        agencyLegal.setState("1");
        if(list.size() == 1){
            agencyLegalMapper.updateById(agencyLegal);
            AgencyLegalCheckLog log = new AgencyLegalCheckLog();
            log.setCreateTime(new Date());//设置创建时间

            log.setLegalCode(list.get(0).getLegalCode());
            log.setState("0");
            agencyLegalCheckLogMapper.insert(log);
        }
    }

    @Override
    public Result queryByInfo(AgencyLegal agencyLegal) {

//        if(null == subjectLegal.getSubjectId()){
//            return Result.error("登陆信息还没有录入，请先完成登录信息注册！");
//        }

        QueryWrapper<AgencyLegal> queryWrapper = new QueryWrapper<AgencyLegal>();
        queryWrapper.eq(null != agencyLegal.getLegalCode(), "legal_code",agencyLegal.getLegalCode());
        queryWrapper.eq(null != agencyLegal.getAgencyName(), "agency_name",agencyLegal.getAgencyName());
        queryWrapper.eq(null != agencyLegal.getAgencyId(),"agency_id",agencyLegal.getAgencyId());
        queryWrapper.eq(null != agencyLegal.getSysUserId(),"sys_user_id",agencyLegal.getSysUserId());

        AgencyLegal agencyLegalNew = agencyLegalMapper.selectOne(queryWrapper);
        if(agencyLegalNew == null){
            return Result.error("代理机构信息不存在，请先完成注册！");
        }

        return Result.ok(agencyLegalNew);
    }


    @Override
    public void check(AgencyLegal agencyLegal) {

        QueryWrapper<AgencyLegal> queryWrapper = new QueryWrapper<AgencyLegal>();
        queryWrapper.eq("agency_id", agencyLegal.getAgencyId());
        List<AgencyLegal> list = agencyLegalMapper.selectList(queryWrapper);

        if(list.size() == 1){
            agencyLegalMapper.updateById(agencyLegal);
        }

        // 1 通过 2 驳回
        if("1".equals(agencyLegal.getState())){
            agencyLegalMapper.updateSysUserRegistState(agencyLegal);
        }



    }


    private SysUser trunUserByAgencyLegal(AgencyLegal agencyLegal){
        SysUser user = new SysUser();

        user.setUsername(agencyLegal.getLegalCode());
        user.setRealname(agencyLegal.getAgencyName());
        user.setIsAgencyRegister(1);

        user.setPassword(agencyLegal.getPassword());
        user.setPlatformArry(agencyLegal.getPlatformArry());

        user.setUserSource(CommonConstant.USER_SOURCE_4);// 会员注册

        return user;
    }


    private boolean addSysUserInfo(SysUser user) {

        String selectedRoles = "1842001997798924290,1869275127898492929";
        String selectedDeparts = "";
        try {
            //先查询 用户是否存在
            SysUser old = sysUserService.getUserByName(user.getUsername());
            if(null == old){
                user.setCreateTime(new Date());//设置创建时间
                String salt = oConvertUtils.randomGen(8);
                user.setSalt(salt);
                String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
                user.setPassword(passwordEncode);
                user.setStatus(1);
                user.setIsAgencyRegister(1);
                user.setDelFlag(CommonConstant.DEL_FLAG_0);
                //用户表字段org_code不能在这里设置他的值
                user.setOrgCode(null);
                // 保存用户走一个service 保证事务
                sysUserService.saveUser(user, selectedRoles, selectedDeparts);
                baseCommonService.addLog("代理机构注册添加，username： " + user.getUsername(), CommonConstant.LOG_TYPE_2, 2);
            }else{
                old.setUsername(user.getUsername());
                String salt = oConvertUtils.randomGen(8);
                old.setSalt(salt);
                String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
                old.setPassword(passwordEncode);
                old.setRealname(user.getRealname());
                old.setUserSource(CommonConstant.USER_SOURCE_4);// 会员注册
                old.setIsAgencyRegister(1);
                old.setPlatformArry(user.getPlatformArry());
                user.setId(old.getId());
                sysUserService.registerEditUser(old, selectedRoles, selectedDeparts);
                baseCommonService.addLog("代理机构注册编辑，username： " + user.getUsername(), CommonConstant.LOG_TYPE_2, 2);
            }
        } catch (Exception e){
            log.error(e.getMessage(), e);
            return false;
        }
        return true;

    }


}
